package club.kingyin.kyblogprogateway.filter;

import club.kingyin.commons.constant.LogConstant;
import club.kingyin.commons.entity.user.Log;
import club.kingyin.commons.response.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

import java.util.Objects;


// 异常统一，错误异常追加到日志
@Order(1)
//@Configuration
public class JsonExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Integer logId = Integer.parseInt(Objects.requireNonNull(exchange.getRequest().getHeaders().getFirst(LogConstant.LOG_ID)));
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // 将返回格式设为JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
        }
        // 改变请求响应返回行为
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();

            Result errorResult = Result.fail(String.valueOf(response.getStatusCode().value()), ex.getMessage(), response.getStatusCode());
            // 添加日志链路
            Log log = new Log();
            log.setId(logId);
            log.setResponse(errorResult);
            // 异常消息发送
            rabbitTemplate.convertAndSend("log.direct","update",log);
            try {
                // 返回ErrorResult
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(errorResult));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }

}